import 'dart:typed_data';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/pages/custom/gift_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
import '../model/giftmodel.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

class MsgScenesPage extends StatefulWidget {

  final String mobile;

  const MsgScenesPage({Key key, this.mobile}) : super(key: key);

  @override
  _MsgScenesPageState createState() => _MsgScenesPageState();
}

class _MsgScenesPageState extends State<MsgScenesPage> {

  GlobalKey globalKey = GlobalKey();
  bool issceenshot = false;
  List<SceneModel> list;
  int sceneIndex = 0;
  String imgUrl = "";
  String sceneTitle = "场景";

  @override
  void initState() {
    super.initState();
    _requestData();
  }

  void _capturePng() async {
    RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List picBytes = byteData.buffer.asUint8List();

    _saveImage(picBytes);
  }

  _saveImage(Uint8List data) async {
    final result = await ImageGallerySaver.saveImage(data);
    if(result != null) {
      AlertTool.showToast("已保存至相册");
    } else {
      AlertTool.showToast("保存失败,请检查相册权限是否开启");
    }

    setState(() {
      issceenshot = false;
    });
  }

  void _requestData() {
    Networktool.request(API.chatgift, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        Autogenerated generatedd = Autogenerated.fromJson(data);
        list = generatedd.data;
        imgUrl = list.first.url;
        if(mounted) setState(() {});
      }
    });
  }

  void _requestSend(GiftModel model) {
    Networktool.request(API.chatgiftorder, params: {"gid": model.id, "mobile": widget.mobile, "des":"备注"}, method: NETWORKHTTPMethod.POST, success: (data){
      if(data != null) {
        AlertTool.showToast("赠送成功");
      }
    },
    fail: (msg) => AlertTool.showToast(msg),);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RepaintBoundary(
        key: globalKey,
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(imgUrl),
              fit: BoxFit.cover
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Offstage(
                offstage: issceenshot,
                child: AppBar(
                  centerTitle: true,
                  elevation: 0,
                  backgroundColor: Colors.transparent,
                  leading: IconButton(
                    onPressed: (){
                      Navigator.of(context).pop();
                    },
                    icon: Image.asset("assets/fanhui.png", color: Colors.white,),
                  ),
                  title: Text(sceneTitle, style: instanceTextStyle(17, Colors.white),),
                ),
              ),
              Spacer(),
              Offstage(
                offstage: issceenshot,
                child: InkWell(
                  onTap: (){
                    sceneIndex += 1;
                    if(sceneIndex >= list.length) sceneIndex = 0;
                    SceneModel m = list[sceneIndex];
                    setState(() {
                      imgUrl = m.url;
                      sceneTitle = m.name;
                    });
                  },
                  child: Padding(
                    padding: const EdgeInsets.only(right: 8.0),
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Image.asset("assets/qiehuan.png"),
                        Positioned(bottom: 3,child: Text("切换", style: instanceTextStyle(11, Colors.white),),)
                      ],
                    ),
                  ),
                ),
              ),
              Offstage(
                offstage: issceenshot,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 50),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      InkWell(
                        onTap: (){
                          setState(() {
                            issceenshot = true;
                          });
                          Future.delayed(const Duration(milliseconds: 100)).then((value) => _capturePng());
                        },
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            Image.asset("assets/zhaoxiangji.png"),
                            Positioned(
                              bottom: 3,
                              child: Text("照相机", style: instanceTextStyle(11, Colors.white),),
                            )
                          ],
                        )
                      ),
                      InkWell(
                        onTap: (){
                          AlertTool.showBottomUserInfoDialog(context, GiftListWidget(list: list[sceneIndex]?.gift, onSendGift: _requestSend,), evelvation: 0);
                        },
                        child: Stack(
                          alignment: Alignment.center,
                          children: [
                            Image.asset("assets/liwu.png"),
                            Positioned(
                              bottom: 3,
                              child: Text("礼物", style: instanceTextStyle(11, Colors.white),),
                            )
                          ],
                        )
                      ),
                    ]
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}